import React from 'react'
import { Row, Col, Button, Table, Select ,Modal ,message} from 'antd'
import '../styles.css'
import Model from "./Model"
import api from "../../../api/api";
import axios from 'axios';
const { Option } = Select;



class FactoryManagement extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      modelData : {
        title: "新增厂区",
        visible: false,
        type: 1,//新增厂区:1,编辑: 2,新增子公司:3
        gridList: {},
        isParent:true
      },
      children:{},
      companyId:0,
      gid:null,
      pageNum:1,
      pageSize:10,
      total: 0,
      factoryList:[],
      isLoding:false,
      
    };
  }


  param = {
    factoryId : null,
    thirdFactoryId : null,
    code : null,
    name : null,
    pcode:null,
    gid : null,
    hrpid : null,
    fullName : null,
    oldFullName : null,
    createTime : null,
    orgCode : null
    
  }
  columns = [

    {
      title: '公司编码',
      dataIndex: 'code',
      key: 'code',
      width: '20%'
    },
    {
      title: '公司名称',
      dataIndex: 'fullName',
      key: 'fullName',
      width: '30%'
    },
    {
      title: '公司简称',
      dataIndex: 'name',
      width: '10%',
      key: 'name'
    },
    {
      title: '更新时间',
      dataIndex: 'createTime',
      width: '20%',
      key: 'createTime'
    },
    {
      title:"公司ID",
      dataIndex: 'factoryId',
      key: 'factoryId',
      width:'0%',
      className: "notShow"

    },
    {
      title: '操作',
      dataIndex: 'option',
      width: '20%',
      key: 'option',
      render: (text, record, index) => {
        return(
          <span>
            <a className="optionMargin" onClick={() => this.onClickAdd(record)}>添加子公司</a>
            <a className="optionMargin" onClick={() => this.onClickEdit(record)}>编辑</a>
            <a className="optionMargin" onClick={() => this.onClickDelete(record.factoryId)}>删除</a>
          </span>
        )
      }
    }
  ];
  data = [];
  onRef = (ref) => {
    this.child = ref
  }

  // eslint-disable-next-line no-dupe-class-members
  componentDidMount() {
    this.getFactoryList();
    this.getSelect();
  }

  
    //选择公司
    handleChange=(value)=> {
      this.setState({
        companyId: value
      },()=>{
        // this.getCompanyInfo();
      })
    }
  

    getCompanyInfo() {
      const that = this;
      let companyId = that.state.companyId
      let url = api.api_URL + "/admin/company/queryCompanyInfoById?companyId="+companyId;
      axios({
        method: 'GET',
        url: url,

        headers: {
          "Authorization": localStorage.getItem('token'),
          "Content-Type": "application/json;charset=UTF-8"
        },
      }).then(function (response) {
        let data = response.data.data.companyInfo
 
        that.setState({
          gid: data.thirdCompanyId
        })
        that.getFactoryList();
      })
        .catch(function (error) {
          console.log(error);
        })
    }

  getFactoryList() {
    const that = this;
    // that.param.gid = that.state.gid;
    that.param.gid = that.state.gid
    that.param.orgCode = localStorage.getItem('orgCode')
    let url = api.api_URL + "/admin/factory/queryFactoryInfoByParamAndPage?pageNum=" + this.state.pageNum + "&pageSize=" + this.state.pageSize;
    axios({
      method: 'POST',
      url: url,
      data: JSON.stringify(that.param),
      headers: {
        "Authorization": localStorage.getItem('token'),
        "Content-Type": "application/json;charset=UTF-8"
      },
    }).then(function (response) {
      let data = response.data.data.list;
      that.data = response.data.data.list.content;
      that.setState({
        total: data.totalSize,
        factoryList : data.content
      })

    })
      .catch(function (error) {
        console.log(error);
      })
  }

  addFactory() {
    const that = this;
    that.param.gid = that.state.gid;

    let url = api.api_URL + "/admin/factory/queryFactoryInfoByParamAndPage?pageNum=" + this.state.pageNum + "&pageSize=" + this.state.pageSize;
    axios({
      method: 'POST',
      url: url,
      data: JSON.stringify(that.param),
      headers: {
        "Authorization": localStorage.getItem('token'),
        "Content-Type": "application/json;charset=UTF-8"
      },
    }).then(function (response) {
      console.log("22222222222222222",response.msg)
      let data = response.data.data.list;
      that.data = data.content;
      that.setState({
        total: data.totalSize
      })

    })
      .catch(function (error) {
        console.log(error);
      })
  }
  //添加
onClickAdd(item) {
  this.setState({
    modelData:{
      title: "新增子公司",
      visible: true,
      type : 3,
      gridList:item,
      isParent:false
    }
  }, () => {
    this.child.clearData()
  });
}
//编辑
onClickEdit(item) {
  this.setState({
    modelData:{
      title: "编辑",
      visible: true,
      type:2,
      gridList:item
    }
  }, () => {
    this.child.initEditData()
  });
}

    //删除
    onClickDelete(item) {
      let that = this;
      let configModel = Modal.confirm({
          title: '删除',
          content: '是否确认删除？',
          onOk: (values) => {
              return new Promise((res, rej) => {
                let url = api.api_URL + "/admin/factory/deleteFactoryInfo?factoryInfoId=" + item;
                  axios({
                      method: 'POST',
                      url: url,
                      headers: {
                          "Authorization": localStorage.getItem('token'),
                          "Content-Type": "application/json;charset=UTF-8"
                      },
                  }).then(function (response) {
                    if(response.data.msg==="成功"){
                      message.success({content:"操作成功"})
                      that.getFactoryList()
                      configModel.destroy();
                    }else{
                      message.error({content:"操作失败"})
                    }
                    
                  })
                      .catch(function (error) {
                          console.log(error);
                      })
              }).catch((e) => console.warn(e));
          },
          onCancel() {
          },
      })
  }

  addcompany() {
    this.setState({
      modelData: {
        title: "新增公司",
        type: 1,
        visible: true,
        isParent:true
      }
    }, () => {
      this.child.clearData()
    });
  }

  //分页
  onBaseClick(current, pageSize) {
    this.setState({
      pageNum: current,
      pageSize: pageSize
    }, () => {
      this.getFactoryList()
    });
  }

  //获取下拉框值
  children = [];
  handleCancel = e => {
    this.setState({
      modelData: {
        visible: false
      },
    });
    this.getFactoryList()
  }

  handleOk = e => {
    this.setState({
      modelData: {
        visible: false
      },
    });
  }
  getSelect() {
    // let data = [
    //   {key: "1", label: "请选择公司"},
    //   {key: "2", label: "公司1"},
    //   {key: "3", label: "公司2"},
    // ]
    // for (let i = 0; i < data.length; i++) {
    //   this.children.push(<Option key={data[i].key}>{data[i].label}</Option>);
    // }
    let that = this;
    let dataList = [];
    let url = api.api_URL+"/admin/company/queryAllCompanyInfoForSelect?orgCode="+localStorage.getItem('orgCode');
    axios.get(url, {
      headers: {
        "Authorization": localStorage.getItem('token'),
        "Content-Type": api.ContentType
      }
    }).then(function (res) {
      if (res.data.code != 1) {
        alert(res.data.msg);
        return;
      }
      let companyInfoList = res.data.data.companyInfoList;
      for (let i = 0; i < companyInfoList.length; i++) {
        let comData = companyInfoList[i];
        const data = {};
        data.key = comData.companyId;
        data.label = comData.companyName;
        dataList[i] = data;
      }
      for (let i = 0; i < dataList.length; i++) {
        that.children.push(<Option key={dataList[i].key}>{dataList[i].label}</Option>);
      }
      that.setState({
          children : that.children
      })
    }).catch(function (err) {
      console.log(err);
    })
  }


  downloadClick = () => {
    let that = this;
    let exportUrl = api.api_URL + "/admin/factory/downFactoryInfoExcel";
    that.param.orgCode = localStorage.getItem("orgCode")
    let data = that.param
    that.exportFile(exportUrl, data)
}

  exportFile(url, data) {
    axios({
        method: 'post',
        url: url,
        data: data,
        responseType: 'blob'
    }).then((res) => {
        const content = res.data;
        const blob = new Blob([content]);
        const fileName = "公司导出数据.xls";
        const selfURL = window[window.webkitURL ? 'webkitURL' : 'URL'];
        let elink = document.createElement('a');
        if ('download' in elink) {
            elink.download = fileName;
            elink.style.display = 'none';
            elink.href = selfURL['createObjectURL'](blob);
            document.body.appendChild(elink);

            // 触发链接
            elink.click();
            selfURL.revokeObjectURL(elink.href);
            document.body.removeChild(elink)
        } else {
            navigator.msSaveBlob(blob, fileName);
        }
    })
}
onclickSearch(){
  console.info("搜索");
  this.setState({
    pageNum:1,
    pageSize:10
  })
  this.getCompanyInfo();
}


  render() {
      const dataSource = this.factoryList;
      var that = this;
      return (
        <div className="girdBg">
            <Row className="searchBox">
              <Col span={12}>
              {/*<Select placeholder="请选择公司" style={{ width: 200 ,marginLeft:30}} onChange={this.handleChange}  allowClear >*/}
                {/*{this.children}*/}
              {/*</Select>*/}
              {/*<Button type='primary' style={{marginLeft: 30}} onClick={this.onclickSearch.bind(this)}>搜索</Button>*/}
              </Col>
              <Col span={12} className="btnRight">
                <Button icon={"save"} type='primary' onClick={this.addcompany.bind(this)}>新增公司</Button>
                {/*<Button shape='circle' type='primary' icon="download" onClick={this.downloadClick}/>*/}
              </Col>
            </Row>
            <Row style={{margin: 30}}>
              <Table
                columns={this.columns}
                dataSource={that.state.factoryList}
                scroll={{x: 'max-content'}} // 加上这条  横向滚动  支持此属性的浏览器内容就不会换行了
                columns={this.columns.map(item => { // 通过配置 给每个单元格添加不换行属性
                  const fun = () => ({style: {whiteSpace: 'nowrap'}});
                  item.onHeaderCell = fun;
                  item.onCell = fun;
                  return item;
                })}
                pagination={{
                  simple: false,
                  current: this.state.pageNum,
                  total: this.state.total,
                  pageSize: this.state.pageSize,
                  showTotal: (count = this.state.total) => {
                    return '共' + count + '条'
                  },
                  onChange: (current, pageSize) => {
                    this.onBaseClick(current, pageSize)
                  }
                }}
                rowKey={record=>record.id}
              />
            </Row>
            <Model data={this.state} handleCancel={this.handleCancel} onRef={this.onRef}/>
        </div>
      )
  }
}
  
  export default FactoryManagement